#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), alpha()
{
    ui->setupUi(this);
        
    this->socket = new QTcpSocket(this);

    // Bouton quitter
    connect(ui->actionSortir, SIGNAL(triggered()), qApp, SLOT(quit()));

    // Bouton parcourir
    connect(ui->parcourir, SIGNAL(clicked()), this, SLOT(displayImage()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

// Bouton parcourir
void MainWindow::on_parcourir_clicked()
{
    this->fileName = this->dialog.getOpenFileName(this, tr("Charger une image"), "./", tr("Images (*.png *.bmp *.jpg)"));
    ui->image->showNormal();
}

IplImage* MainWindow::QImage2IplImage(QImage *qimg)
{
    IplImage *imgHeader = cvCreateImageHeader( cvSize(qimg->width(), qimg->height()), IPL_DEPTH_8U, 4);
    imgHeader->imageData = (char*) qimg->bits();

    uchar* newdata = (uchar*) malloc(sizeof(uchar) * qimg->byteCount());
    memcpy(newdata, qimg->bits(), qimg->byteCount());
    imgHeader->imageData = (char*) newdata;

    //cvClo
    return imgHeader;
}

// Charge une image
void MainWindow::displayImage()
{
    QImage qImage;
    qImage.load(this->fileName);

    QPixmap monPixmap;
    monPixmap = QPixmap::fromImage(qImage);
    monPixmap = monPixmap.scaled(ui->image->size(), Qt::AspectRatioMode(Qt::IgnoreAspectRatio), Qt::FastTransformation);

    // Application de la pixmap
    ui->image->setPixmap(monPixmap);

    this->visage = new C_dessine_visage(this->QImage2IplImage(&qImage));

    //QString taille = profile.getvector();
    //qDebug()<<"ee"<<profile.getvector();
}

// Envoyer au robot
void MainWindow::on_envoyer_clicked()
{
    QString trameEnd;
    char tmp;
    QString trame = ui->nomPersonne->text().simplified().toUpper();

    for (int x=0;x<trame.size();x++)
    {
        tmp = trame.toUpper().at(x).toAscii();

        if(tmp==QChar(' ')){
            trameEnd.append(QChar('#'));
            trameEnd.append(QChar(' '));
        }
        else if (!this->alpha.contains(tmp))
        {
            trameEnd.append(QChar('F'));
            trameEnd.append(QChar(' '));
        }
        else
        {
            QVector<elementAlpha> *elem  = this->alpha.value(tmp);
            for(int i=0;i<elem->size();i++){
                trameEnd.append(QChar(elem->at(i).type));
                QVector<QPointF> *points = elem->at(i).coordonnee;
                 trameEnd.append(QChar(' '));
                 trameEnd.append(QString::number(points->size()));
                 trameEnd.append(QChar(' '));

                for(int u=0;u<points->size();u++){
                    trameEnd.append(QString::number(points->at(u).x(),'g',6));
                    trameEnd.append(QChar(' '));
                    trameEnd.append(QString::number(points->at(u).y()));
                    trameEnd.append(QChar(' '));
                }
            }
            trameEnd.append(QChar('F'));
            trameEnd.append(QChar(' '));
        }
    }

    //trameEnd.append(QChar('Q'));
    trameEnd = trameEnd.simplified().toUpper();

    this->envoie(trameEnd);
}

void MainWindow::envoie(QString chaine)
{
    this->socket->abort(); // On désactive les connexions précédentes s'il y en a
    this->socket->connectToHost(this->ipAdress, this->port); // On se connecte au serveur demandé
    //this->socket->connectToHost("172.16.22.6", 2001); // On se connecte au serveur demandé

    QStringList trameEnds = this->splitNumber(chaine,255);

    for(int i=0;i<trameEnds.size();i++)
        this->socket->write(trameEnds.at(i).toStdString().c_str(), trameEnds.at(i).size());

}

QStringList MainWindow::splitNumber(QString chaine,int cute)
{
    QStringList chaines;
    int num = chaine.size()/cute;

    if(chaine.size()<cute)
    {
        chaines.append(chaine);
    }
    else
    {
        for(int i=0;i<num;i++) chaines.append(chaine.mid(i,i+cute));
    }

    return chaines;
}

void MainWindow::initAlphabet()
{
    QRegExp alpha ("^ALPHA");
    QRegExp cc ("^C");
    QRegExp ll ("^L");
    QRegExp pp ("^P");
    char lastChar = ' ';
    QString chemin = QApplication::applicationDirPath();

    QString fichier = QFileDialog::getOpenFileName(this, tr("Open Alpha"), chemin, tr("Alpha Files (*.alpha)"));

    typeAlpha tligne = l;
    typeAlpha tpoint = p;
    typeAlpha tcercle = c;

    QFile file(fichier);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream flux(&file);

   do {
       QString ligne = flux.readLine();

       if (ligne.contains(alpha)){
           lastChar = ligne.split(",").at(1).trimmed().at(0).toAscii();
            this->alpha.insert(lastChar,new QVector<elementAlpha>());
       }

       if (ligne.contains(cc) || ligne.contains(pp) || ligne.contains(ll))
       {
           this->alpha.value(lastChar)->append(elementAlpha());

            if(ligne.contains(cc)) this->alpha.value(lastChar)->last().type = tcercle;
            if(ligne.contains(pp)) this->alpha.value(lastChar)->last().type = tpoint;
            if(ligne.contains(ll)) this->alpha.value(lastChar)->last().type = tligne;

           this->alpha.value(lastChar)->last().coordonnee = new QVector<QPointF>();

           QStringList list = ligne.simplified().split(",");

           for(int i=0;(i+1)<list.size();i+=2)
           {
                this->alpha.value(lastChar)->last().coordonnee->append(QPointF());
                this->alpha.value(lastChar)->last().coordonnee->last().setX(list.at(i+1).toFloat());
                this->alpha.value(lastChar)->last().coordonnee->last().setY(list.at(i+2).toFloat());
           }
       }
   } while(!flux.atEnd());
}

void MainWindow::on_btnInitParam_clicked()
{
    this->port = ui->inputPortSrv->text().toInt();
    this->ipAdress = QHostAddress(ui->inputAdressSrv->text());

    if (this->ipAdress.isNull()) this->ipAdress = QHostAddress("172.16.22.6");
    if (this->port == 0) this->port = 2001;
}

void MainWindow::on_initAlpha_clicked()
{
    this->initAlphabet();
}

void MainWindow::on_pushButton_clicked()
{
    /*
    vector<S_point> v = this->visage->getvector(3);

    QString chaine;
    chaine.append(QChar('D'));
    chaine.append(QChar(' '));
    chaine.append(QString::number(v.size()));
    chaine.append(QChar(' '));

    for(unsigned int i=0;i<v.size();i++){

    }

    chaine.append(QChar('F'));
    this->envoie(chaine.trimmed());
*/
    QString chaine;
    chaine.append(QChar('D'));
    chaine.append(QChar(' '));
    chaine.append(QString::number(4));
    chaine.append(QChar(' '));
    chaine.append(QString::number(v.at(i).x));
    chaine.append(QChar(' '));
    chaine.append(QString::number(v.at(i).y));
    chaine.append(QChar(' '));

}
